import React, { Component } from 'react'
import TodoItems from './TodoItems'

import './../css/TodoList.css'

class TodoList extends Component {

    constructor(props) {
        super(props)

        this.state = {
            items: []
        }

        this.deleteItem = this.deleteItem.bind(this)

        this.addItem = (e) => {
            let itemArray = this.state.items

            if (this._inputElement.value !== "") {

                itemArray.unshift({
                    text: this._inputElement.value,
                    key: Date.now()
                })

                this.setState({
                    items: itemArray
                })

                this._inputElement.value = ""
            }

            console.log(itemArray)

            e.preventDefault()
        }
    }
    
    deleteItem(key) {
        let filteredItems = this.state.items.filter(function (item) {
            return (item.key !== key)
        })

        this.setState({
            items: filteredItems
        })
    }

    render() {
        return (
            <div className="todoListMain">
                <div className="header">
                    <form onSubmit={this.addItem}>
                        <input ref={(a) => this._inputElement = a}
                        placeholder="添加待办事项"></input>
                        <button type="submit">确定</button>
                    </form>
                </div>
                <TodoItems entries={this.state.items} 
                            delete={this.deleteItem}/>
            </div>
        )
    }
}

export default TodoList